<template>
    <div class="app-container">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="会员昵称" prop="memberName">
          <el-input
            v-model="queryParams.memberName"
            placeholder="请输入会员昵称"
            clearable
          />
        </el-form-item>
        <el-form-item label="会员账号" prop="memberAccount">
          <el-input
            v-model="queryParams.memberAccount"
            placeholder="请输入会员账号"
            clearable
          />
        </el-form-item>
  
        <el-form-item label="上级会员账号" prop="parentMemberAccount">
          <el-input
            v-model="queryParams.parentMemberAccount"
            placeholder="请输入上级会员"
            clearable
          />
        </el-form-item>
        <el-form-item label="会员状态" prop="memberStatus">
          <el-select
            v-model="queryParams.memberStatus"
            placeholder="会员状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.adv_member_status"
              :label="dict.label"
              :value="dict.value"
              :key="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否主播" prop="isBroadcast">
          <el-select
            v-model="queryParams.isBroadcast"
            placeholder="是否主播"
            clearable
          >
            <el-option
              v-for="dict in dict.type.adv_is_broadcast"
              :label="dict.label"
              :value="dict.value"
              :key="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="deliverGoods"
            v-hasPermi="['system:role:add']"
            >小程序发货</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="initAllData"
            v-hasPermi="['system:role:add']"
            >系统数据初始化</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="compareResourcesDelete"
            >清除无用文件</el-button
          >
        </el-col>
       
        <!-- <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:role:edit']"
            >修改</el-button
          >
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:members:export']"
            >删除</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:members:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
  
      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="roleList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="会员昵称" align="center" prop="memberName" />
        <el-table-column label="会员账号" align="center" prop="memberAccount" />
        <!-- <el-table-column label="会员地址" align="center" prop="address" /> -->
        <el-table-column label="上级会员账号" align="center" prop="parentMemberAccount" />
        <el-table-column label="佣金比例" align="center" prop="payRate" />
        <el-table-column label="会员状态" align="center" prop="memberStatus">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.adv_member_status"
              :value="scope.row.memberStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="营销状态" align="center" prop="isSaler">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.adv_is_saler"
              :value="scope.row.isSaler"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否主播" align="center" prop="isBroadcast">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.adv_is_broadcast"
              :value="scope.row.isBroadcast"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="220px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="initOne(scope.row)"
              v-hasPermi="['system:role:edit']"
              >个人数据初始化</el-button
            >
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:role:remove']"
              >删除</el-button
            > -->
            <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-user-solid"
            @click="handleStop(scope.row)"
            v-hasPermi="['system:role:remove']"
           v-if="scope.row.memberStatus == 1"
            > 拉黑 -->
          <!-- </el-button>
          <el-button
           v-else 
            size="mini"
            type="text"
            icon="el-icon-user-solid"
            @click="handleStart(scope.row)"
            v-hasPermi="['system:role:remove']"
            >启用
            </el-button> -->
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-user-solid"
              @click="handleSucessSaler(scope.row,1)"
              v-hasPermi="['system:role:remove']"
             v-if="scope.row.isSaler != 1"
              > 营销审核通过 -->
            <!-- </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-user-solid"
              @click="handleSaler(scope.row,0)"
              v-hasPermi="['system:role:remove']"
             v-if="scope.row.isSaler != 0"
              > 营销审核拒绝 -->
            <!-- </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-user-solid"
              @click="handleSaler(scope.row,2)"
              v-hasPermi="['system:role:remove']"
             v-if="scope.row.isSaler != 2"
              > 取消审核
            </el-button> -->
          
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改用户和角色关联对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="会员昵称" prop="memberName">
            <el-input
              v-model="form.memberName"
              placeholder="请输入会员昵称"
              clearable
              readonly
            />
          </el-form-item>
          <el-form-item label="会员账号" prop="memberAccount">
            <el-input
              v-model="form.memberAccount"
              placeholder="请输入会员账号"
              clearable
              readonly  
            />
          </el-form-item>
  <!--
          <el-form-item label="(选择地区)" prop="busAreasId">
            <el-cascader
              :value="form.busAreasId"
              :options="areaCascaderOptions"
              :props="areaCascaderProps"
              @change="areaCascaderChange"
              ref="Houseref"
              separator="-"
              clearable
            ></el-cascader>
          </el-form-item>
  -->
          <!-- <el-form-item label="会员地址" prop="address">
            <el-input
              v-model="form.address"
              placeholder="请输入会员地址"
              clearable
               style="width: 300px;" 
               readonly
            />
          </el-form-item> -->
            <!--
            <el-cascader
              :value="form.busAreasId"
              :options="areaCascaderOptions"
              :props="areaCascaderProps"
              @change="areaCascaderChange"
              ref="Houseref"
              separator="-"
              clearable
               style="width: 30px;" 
            ></el-cascader>
            -->
          
  
  
          <el-form-item label="上级会员" prop="parentMemberAccount">
            <el-select
              v-model="form.parentMemberAccount"
              placeholder="上级会员"
              clearable
              readonly
              disabled  
            >
              <el-option
                v-for="item in roleList"
                :label="item.memberName"
                :value="item.advMembersId"
                :key="item.advMembersId"
              />
            </el-select>
          </el-form-item>
  
          <el-form-item label="会员状态" prop="memberStatus">
            <el-select
              v-model="form.memberStatus"
              placeholder="会员状态"
              clearable
            >
              <el-option
                v-for="dict in dict.type.adv_member_status"
                :label="dict.label"
                :value="dict.value"
                :key="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否主播" prop="isBroadcast">
            <el-select
              v-model="form.isBroadcast"
              placeholder="是否主播"
              clearable
            >
              <el-option
                v-for="dict in dict.type.adv_is_broadcast"
                :label="dict.label"
                :value="dict.value"
                :key="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="佣金比例" prop="payRate">
            <el-input
              v-model="form.payRate"
              placeholder="请输入佣金比例"
              clearable
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import {
    listMembers,
    addMembers,
    updateMembers,
    delMembers,
    AddShare,
    initAll,
    initOne
  } from "@/api/server/members.js";
  
  import { getAreaList,getAreas,compareResourcesDeleteAPI, deliverGoodsApi } from "@/api/server/areas.js";
  
  export default {
    name: "Member",
    dicts: ["adv_is_broadcast", "adv_member_status","adv_is_saler"],
    data() {
      return {
        //--------------地区下拉相关数据-----------------//
        //areaCascaderValue: "",
        areaCascaderOptions: [], //  初始的选项 第一级节点
        areaCascaderProps: {
          //  地区级联选择、懒加载、单选
          expandTrigger: "click", //  悬停触发
          checkStrictly: true, //  单选
          lazy: true, //懒加载
          lazyLoad(node, resolve) {
            //  node为当前点击的节点
            //  这里不能调用 methods对象 中的方法
            getAreaList(node.value).then(
              (res) => {
                let single=res.data;
                const nodes = single.map((item) => ({
                  value: item.busAreasId,
                  label: item.areaName,
                }));
                resolve(nodes);
              },
              (err) => {
                console.log(err);
              }
            );
          },
        },
        //--------------------------------------//
        value: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          memberName: undefined,
          memberAccount: undefined,
          address: undefined,
          parentMemberAccount: undefined,
          memberStatus: undefined,
          isBroadcast: undefined,
        },
        ids: [],
        showSearch: true,
        single: false,
        multiple: false,
        loading: false,
        currentPage4: 1,
        roleList: [],
        total: 0,
        title: "",
        open: false,
        form: {},
        rules: {
          memberName: [
            { required: true, message: "请输入会员昵称", trigger: "blur" },
          ],
          memberAccount: [
            { required: true, message: "请输入会员账号", trigger: "blur" },
          ],
          payRate: [
            { required: true, message: "请输入佣金比例", trigger: "blur" },
          ],
          /*
          areaCascaderValue: [
            { required: true, message: "请输入会员所属地区", trigger: "blur" },
          ],
          */
          // address: [
          //   { required: true, message: "请输入会员地址", trigger: "blur" },
          // ],
          memberStatus: [
            { required: true, message: "请选择会员状态", trigger: "change" },
          ],
          isBroadcast: [
            { required: true, message: "请选择是否主播", trigger: "change" },
          ],
        },
      };
    },
    mounted() {
      this.funGetAreaList(0);
    },
    created() {
      this.getList();
    },
  
    methods: {
      deliverGoods() {
        deliverGoodsApi().then((response) => {
          console.log("获取到的数据", response)
        })
      },
      compareResourcesDelete() {
        compareResourcesDeleteAPI().then((response) => {
          console.log("清理文件的结果", response)
          this.$message({
            type: "info",
            message: response.message,
          });
        })
      },
    initAllData() {
        this.$confirm("系统所有业务数据将全部删除，是否确定操作?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            console.log("初始化系统数据")
            initAll().then((response) => {
              this.$message({
                type: "info",
                message: response.message,
              });
            })
        }).catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
        });
    },
    initOne(row) {
        this.$confirm("除会员个人基本信息外，其它数据将全部删除，是否确定操作?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            console.log("初始化个人数据")
            initOne(row).then((response) => {
              this.$message({
                type: "info",
                message: response.message,
              });
            })
        }).catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
        });
    },
      handleSucessSaler(row,status){
        this.$confirm("是否提交该操作, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            row.isSaler = status;
            AddShare(row)
              .then(() => {
                this.$message({
                  type: "success",
                  message: "提交成功!",
                });
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "提交失败!",
                });
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      },
      //营销审批
      handleSaler(row,status) {
        this.$confirm("是否提交该操作, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            row.isSaler = status;
            updateMembers(row)
              .then(() => {
                this.$message({
                  type: "success",
                  message: "提交成功!",
                });
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "提交失败!",
                });
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      },
      funGetAreaList(id) {
        getAreaList(id).then(
          (res) => {
            for (let i = 0; i < res.data.length; i++) {
              let temp = {
                label: res.data[i].areaName,
                value: res.data[i].busAreasId,
              };
              this.areaCascaderOptions.push(temp);
            }
          },
          (err) => {
            console.log(err);
          }
        );
      },
  
      areaCascaderChange(value) {
       // console.log(label);
         let tempArr = value;      
         if (tempArr !== "" && tempArr !== null && tempArr !== undefined) {
            // this.form.busAreasId = tempArr[tempArr.length - 1];
            this.form.busAreasId=tempArr[tempArr.length - 1];
            getAreas(this.form.busAreasId).then((result) => {
               this.form.address=result.data.fullPathCn;
             });
          }
      },
  
      handleChange(value) {
        console.log(value);
      },
      handleQuery() {
        console.log(this.queryParams);
        listMembers(this.queryParams)
          .then((result) => {
            this.roleList = result.rows;
            console.log(result);
          })
          .catch((error) => {
            console.log(error);
          });
      },
      resetQuery() {
        
      },
      handleExport() {
        this.download('/system/members/export', {
          ...this.queryParams
        }, `会员资料_${new Date().getTime()}.xlsx`)
      },
      getList() {
        listMembers(this.queryParams)
          .then((result) => {
          console.log("000000000000000");
          console.log(result);
          this.roleList = result.rows;
          this.total = result.total;
          })
          .catch((error) => {
            console.log(error);
          });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.advMembersId);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.getList();
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          memberName: undefined,
          memberAccount: undefined,
          address: undefined,
          parentAccount: undefined,
          memberStatus: undefined,
          isBroadcast: undefined,
        };
        this.resetForm("form");
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.userId);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加会员";
      },
      handleUpdate(row) {
        this.reset();
        console.log(row);
        /*
        getAreas(row.busAreasId).then((result) => {
            this.form.address=result.data.fullPathCn;
        });
        */
        
        this.form = row;
        this.open = true;
        this.title = "修改会员";
      },
      handleDelete(row) {
        this.$confirm("此操作将永久删除该会员, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            const param = row.advMembersId | this.ids;
            delMembers(param)
              .then((response) => {
                console.log(response);
                if (response.statusCode == "404") {
                  this.$message({
                    type: "error",
                    message: response.message,
                  });
                } else {
                  this.$message({
                    type: "success",
                    message: response.message,
                  });
                }
                this.getList();
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "删除失败!",
                });
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      submitForm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.title === "添加会员") {
              addMembers(this.form)
                .then((response) => {
                  this.getList();
                })
                .catch((error) => {
                  this.$message({
                    type: "error",
                    message: "发生意外, 提交失败!",
                  });
                });
              this.$message({
                type: "success",
                message: "添加成功!",
              });
              this.open = false;
            }
            if (this.title === "修改会员") {
              if (this.form.advMembersId === this.form.parentAccount) {
                this.$message({
                  type: "error",
                  message: "不能添加自己为自己的上级会员",
                });
              } else {
                updateMembers(this.form)
                  .then((response) => {
                    this.getList();
                  })
                  .catch((error) => {
                    this.$message({
                      type: "error",
                      message: "发生意外, 提交失败!",
                    });
                  });
                this.$message({
                  type: "success",
                  message: "提交成功!",
                });
                this.open = false;
              }
            }
          } else {
            this.$message({
              type: "error",
              message: "表单验证失败!",
            });
          }
        });
      },
      handleSolid(row) {
        this.$confirm("此操作将永久拉黑该会员, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$message({
              type: "success",
              message: "拉黑成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消拉黑",
            });
          });
      },
      handleStop(row) {
        this.$confirm("此操作将永久禁用该会员, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            row.memberStatus = "0";
            updateMembers(row)
              .then(() => {
                this.$message({
                  type: "success",
                  message: "禁用成功!",
                });
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "禁用失败!",
                });
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消禁用",
            });
          });
      },
  
      handleStart(row) {
        this.$confirm("此操作将启用该会员, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            row.memberStatus = "1";
            updateMembers(row)
              .then(() => {
                this.$message({
                  type: "success",
                  message: "启用成功!",
                });
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "禁用失败!",
                });
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消禁用",
            });
          });
      },
    },
  };
  </script>
  
  <style>
  </style>
  
  